import logging
from offline_calc.handler import OfflineCalculationHandler
from django.conf import settings
from common.dwc.maestro import user_analysis_handler
from event_rule.dwc.user_event_rule.rule_config import CONFIG
from common.const import IntervalType

_LOGGER = logging.getLogger(__name__)


class Command(OfflineCalculationHandler):
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.index_list = settings.DWC_INDEX
        self.event_config = CONFIG
        self.event_handler_mapper = dict(
            pay_ability=user_analysis_handler.user_pay_ability_report_handler,
            new_user_stay=user_analysis_handler.new_user_stay_report_handler,
            continuous_recharge=user_analysis_handler.continuous_recharge_report_handler,
            active_user_analysis=user_analysis_handler.active_user_analysis_handler,
            game_stage_analysis=user_analysis_handler.game_stage_analysis_handler,
        )

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)

    def get_event_handler(self, op_event_name):
        return self.event_handler_mapper.get(op_event_name)

    def handle(self, **kwargs):
        super(Command, self).handle(**kwargs)
        merchant = kwargs['merchant']
        target_event = kwargs['target_event']
        self.index_list = self.index_list if not merchant else [index for index in self.index_list if index == merchant]
        self.event_config = self.event_config if not target_event else {
            event_name: rule for event_name, rule in self.event_config.items() if event_name == target_event}
        self.event_config = {event_name: rule for event_name, rule in self.event_config.items()
                             if not rule.get('real_time_report', False)}

        for index in self.index_list:
            window_visited = {}
            for op_event_name, config in self.event_config.items():
                interval_type_list = config.get('interval_type_list', [])
                for interval_type_value in interval_type_list:
                    window_list = self.get_window_interval(interval_type_value, config.get('day_to_calc', [0]))
                    for window in window_list:
                        if not self.check_merchant_start_time(IntervalType.DAY, index, window):
                            continue
                        print(op_event_name, window, interval_type_value)
                        event_handler = self.get_event_handler(op_event_name)
                        if event_handler:
                            try:
                                self.pool.apipe(self.start_execution, event_handler, IntervalType.DAY, op_event_name,
                                                self.base_time, index, window,
                                                dict(interval_type=IntervalType.DAY, base_time=self.base_time,
                                                     last_window=window, event_name=op_event_name, event_rule=config,
                                                     index=index))
                            except Exception as e:
                                _LOGGER.exception('ES Create Report Error (%s) %s', op_event_name, e)
                            window_visited.setdefault(op_event_name, {})
                            window_visited[op_event_name].setdefault(interval_type_value, [])
                            window_visited[op_event_name][interval_type_value].append(window)
        self.pool.close()
        self.pool.join()
